package main

import (
	"WebServer/dataConst"
	"WebServer/middleware"
	"WebServer/server"
	"WebServer/sql"
	"WebServer/utools"
	"errors"
	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/cors"
)

var (
	app *fiber.App
)

func main() {
	server.APIServer(app.Group("/api"))
	error := app.Listen(":8081")
	if error != nil {
		println("端口监听失败")
	} else {
		println("端口监听成功")
	}
}

func init() {
	go utools.InitDB(dataConst.BaseConn)
	token := middleware.NewToken()
	token.AddPath(dataConst.TokenRouter...)
	token.Use(TokenValidation)
	app = fiber.New()   //初始化服务器实例
	app.Use(cors.New()) //启动跨域协议
	app.Use(token.Handler())
}

func TokenValidation(ctx *fiber.Ctx, token, origin string) error {
	if count, err := sql.VerifyUserSql(token, origin); err != nil || count != 1 { //检验数据库中是否存在此token
		return errors.New("error token")
	} else {
		return nil
	}
}
